package src.utils.resource;

import java.io.InputStream;
import java.net.URL;

class ClassLoaderWrapper {
	
	ClassLoader defaultClassLoader;
	ClassLoader systemClassLoader;
	
	ClassLoaderWrapper() {
		try {
			systemClassLoader = ClassLoader.getSystemClassLoader();
		}
		catch (SecurityException ignored) {}
	}
	
	public URL getResourceAsURL(String resource) {
		return getResourceAsURL(resource, getClassLoaders(null));
	}
	
	public URL getResourceAsURL(String resource, ClassLoader classLoader) {
		return getResourceAsURL(resource, getClassLoaders(classLoader));
	}
	
	public InputStream getResourceAsStream(String resource) {
		return getResourceAsStream(resource, getClassLoaders(null));
	}
	
	public InputStream getResourceAsStream(String resource, ClassLoader classLoader) {
		return getResourceAsStream(resource, getClassLoaders(classLoader));
	}
	
	public Class<?> classForName(String name) throws ClassNotFoundException {
		return classForName(name, getClassLoaders(null));
	}
	
	public Class<?> classForName(String name, ClassLoader classLoader) throws ClassNotFoundException {
		return classForName(name, getClassLoaders(classLoader));
	}
	
	InputStream getResourceAsStream(String resource, ClassLoader[] classLoaderArray) {
		for (ClassLoader classLoader : classLoaderArray) {
			if (null != classLoader) {
				InputStream returnValue = classLoader.getResourceAsStream(resource);
				if (null == returnValue) returnValue = classLoader.getResourceAsStream("/" + resource);
				if (null != returnValue) return returnValue;
			}
		}
		
		return null;
	}
	
	URL getResourceAsURL(String resource, ClassLoader[] classLoaderArray) {
		URL url;
		
		for (ClassLoader classLoader : classLoaderArray) {
			if (null != classLoader) {
				url = classLoader.getResource(resource);
				if (null == url) url = classLoader.getResource("/" + resource);
				if (null != url) return url;
			}
		}
		
		return null;
	}
	
	Class<?> classForName(String name, ClassLoader[] classLoaderArray) throws ClassNotFoundException {
		for (ClassLoader classLoader : classLoaderArray) {
			if (null != classLoader) {
				try {
					Class<?> clazz = Class.forName(name, true, classLoader);
					if (null != clazz) return clazz;
				}
				catch (ClassNotFoundException e) {}
			}
		}
		
		throw new ClassNotFoundException("Cannot find class: " + name);
	}
	
	ClassLoader[] getClassLoaders(ClassLoader classLoader) {
		return new ClassLoader[] {
				classLoader,
				defaultClassLoader,
				Thread.currentThread().getContextClassLoader(),
				getClass().getClassLoader(),
				systemClassLoader
		};
	}
}
